//
//  NYConmentViewController.m
//  百思不得姐
//
//  Created by Apple on 15/8/31.
//  Copyright (c) 2015年 Neal. All rights reserved.
//

#import "NYConmentViewController.h"
#import "NYCommentCell.h"
#import "NYAllViewCell.h"
#import <MJRefresh.h>
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
#import <SVProgressHUD.h>
#import "NYTopicModel.h"
#import "NYTopConment.h"

static NSString *ID = @"topicCell";
static NSString *Commentcell = @"Commentcell";
@interface NYConmentViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *table_View;
@property (weak, nonatomic) IBOutlet UIView *toolBar;
/* 最热评论 */
@property(nonatomic , strong) id top_cmt;
/* manager */
@property(nonatomic , weak) AFHTTPSessionManager *manager;
/* 热门评论 */
@property(nonatomic , strong) NSMutableArray *hotComments;
/* 最新评论 */
@property(nonatomic , strong) NSMutableArray *lastestComments;


@end

@implementation NYConmentViewController
- (AFHTTPSessionManager *)manager
{
    if (_manager == nil) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (NSMutableArray *)hotComments
{
    if (_hotComments == nil) {
        _hotComments = [NSMutableArray array];
    }
    return _hotComments;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"评论";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(click) image:[UIImage imageNamed:@"comment_nav_item_share_icon"] Highlightedimage:[UIImage imageNamed:@"comment_nav_item_share_icon_click"]];
    
    [self setupTableView];

    [self setupRefresh];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboaedDidChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

}
- (void)setupRefresh
{
    self.table_View.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [self.table_View.header beginRefreshing];
    
    self.table_View.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
}
- (void)loadNewData
{
    // 取消之前的所有请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];

    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"]= @"dataList";
    parameters[@"c"]= @"comment";
    parameters[@"data_id"] = self.topic.ID;
    parameters[@"hot"] = @1;
    NYWeakSelf;
   [self.manager GET:NYBaseURL parameters:parameters success:^(NSURLSessionDataTask * task, id responseObject) {
       if ([responseObject isKindOfClass:[NSArray class]]) {
           weakSelf.table_View.header.hidden = YES;
           return ;
       }
       
       weakSelf.hotComments = [NYTopConment objectArrayWithKeyValuesArray:responseObject[@"hot"]];
       weakSelf.lastestComments = [NYTopConment objectArrayWithKeyValuesArray:responseObject[@"data"]];
       [weakSelf.table_View reloadData];
       [weakSelf.table_View.header endRefreshing];

       if (weakSelf.lastestComments.count >= [responseObject[@"total"]intValue ]) {
           weakSelf.table_View.header.hidden = YES;
           
       }
    } failure:^(NSURLSessionDataTask * task, NSError * error) {
        
    }];
}
- (void)loadMoreData
{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"]= @"dataList";
    parameters[@"c"]= @"comment";
    parameters[@"data_id"] = self.topic.ID;
    parameters[@"lastcid"] = [[self.lastestComments lastObject] ID];
    
    
    NYWeakSelf;
    [self.manager GET:NYBaseURL parameters:parameters success:^(NSURLSessionDataTask * task, id responseObject) {
        if ([responseObject isKindOfClass:[NSArray class]]) {
            weakSelf.table_View.footer.hidden = YES;
            return ;
        }
        
        NSArray *newComments = [NYTopConment objectArrayWithKeyValuesArray:responseObject[@"data"]];
        [weakSelf.lastestComments addObjectsFromArray:newComments];
        
        [weakSelf.table_View reloadData];
        
        if (weakSelf.lastestComments.count>= [responseObject[@"total"]intValue]) {
            weakSelf.table_View.footer.hidden = YES;
        } else {
            [weakSelf.table_View.footer endRefreshing];
        }
        
    } failure:^(NSURLSessionDataTask * task, NSError * error) {
        [weakSelf.table_View.footer endRefreshing];

    }];

}
- (void)setupTableView
{
    self.table_View.backgroundColor = NYGlobalBg;
    
    if (self.topic.top_cmt) {
        self.topic.top_cmt = self.top_cmt;
        self.topic.top_cmt = nil;
        self.topic.cellHeight = 0;
    }
    UIView *headerView = [[UIView alloc]init];
    NYAllViewCell *cell = [NYAllViewCell viewFromXib];
    cell.topic = self.topic;
    cell.frame = CGRectMake(0, 0, NYScreenW, self.topic.cellHeight);
    [headerView addSubview:cell];
    
    headerView.height = cell.height + Margin;
    self.table_View.tableHeaderView = headerView;
    
    [self.table_View registerNib:[UINib nibWithNibName:@"NYCommentCell" bundle:nil] forCellReuseIdentifier:Commentcell];

    self.table_View.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.table_View.estimatedRowHeight = 100;
    
    self.table_View.rowHeight = UITableViewAutomaticDimension;
    
}
- (void)keyboaedDidChangeFrame:(NSNotification *)note
{
    double duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        CGFloat keyboardY = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
        CGFloat toobarY = keyboardY - NYScreenH;
        self.toolBar.transform = CGAffineTransformMakeTranslation(0, toobarY);
        
    }];
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if (self.top_cmt) {
        self.topic.top_cmt = self.top_cmt;
        self.topic.cellHeight = 0;
    }
}
- (void)click
{
}

#pragma mark -UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.hotComments.count) {
        return 2;
    }
    if (self.lastestComments.count) {
        return 1;
    }
    return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0&&self.hotComments.count) {
        return self.hotComments.count;
    } else {
        return self.lastestComments.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NYTopConment *comment = nil;
    if (indexPath.section == 0 && self.hotComments.count) {
        comment = self.hotComments[indexPath.row];
    }else
    {
        comment = self.lastestComments[indexPath.row];
    }
    
    NYCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:Commentcell];
    
    cell.comment = comment;

    
    return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section==0&&self.hotComments.count) return  @"热门评论";
    return @"最新评论";
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

/**
 *  menu控制器的使用
 *
 */
- (BOOL)canBecomeFirstResponder
{
    return YES;
}
- (BOOL)resignFirstResponder
{
    UIMenuController *menu = [UIMenuController sharedMenuController];
    menu.menuItems = nil;
    return [super resignFirstResponder];

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    UIMenuController *menucontroller = [UIMenuController sharedMenuController];
    if (menucontroller.menuItems) {
        menucontroller.menuItems = nil;
        return;
    }
    [self becomeFirstResponder];

    NYCommentCell *cell = (NYCommentCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    [menucontroller setTargetRect:cell.bounds inView:cell];
    
    menucontroller.menuItems = @[
                                 [[UIMenuItem alloc]initWithTitle:@"顶" action:@selector(ding)],

                                 [[UIMenuItem alloc]initWithTitle:@"回复" action:@selector(replay)],

                                 [[UIMenuItem alloc]initWithTitle:@"举报" action:@selector(warning)]
                                 ];
    [menucontroller setMenuVisible:YES animated:YES];
    
    
}
- (void)ding
{
    NYLog(@"%s",__func__);
}
- (void)replay
{
    NYLog(@"%s",__func__);

}
- (void)warning
{
    NYLog(@"%s",__func__);

}
@end
